package com.gitee.bluebird;

import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class CommandHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger("CommandHandler");
    private Map<Short, Command> commands;

    private static final Command NOT_FOUND_COMMAND =
            (ctx, packet) -> LOGGER.error("not found command:{}", packet.getCode());


    public CommandHandler() {
        commands = new HashMap<>();
    }

    public void regist(Command command) {
        short code = command.getClass().getAnnotation(Cmd.class).code();
        Command old;
        if ((old = commands.putIfAbsent(code, command)) != null) {
            throw new RuntimeException("repeated command(" + old.getClass().getName() + "," + command.getClass().getName() + ") code:" + code);
        }
    }

    public Command getCommand(short code) {
        return commands.getOrDefault(code, NOT_FOUND_COMMAND);
    }
}
